##########################################################################################
library(reshape)
library(ggplot2)
library(data.table)
#library(ggh4x)
library(patchwork)
library(cowplot)
library(optparse)

##########################################################################################

option_list <- list(

  make_option(c("--mutRate_file"), type = "character"),
  make_option(c("--driver_list"), type = "character"),
  make_option(c("--out_path"), type = "character")
)

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

if(1!=1){
  mutRate_file <- "MutRate.tsv"
  driver_list <- "All_driver.list"
}


mutRate_file <- opt$mutRate_file
out_path <- opt$out_path
driver_list <- opt$driver_list

dat_mutRate_tmp <- fread(mutRate_file)
driver_list <- fread(driver_list)

dat_mutRate_tmp <- subset( dat_mutRate_tmp , Hugo_Symbol %in% driver_list$Gene_Symbol)
dat_mutRate_tmp <- dat_mutRate_tmp[,c("Hugo_Symbol" , "Class" , "From" , "MutRate")]
dat_mutRate_tmp <- cast(dat_mutRate_tmp , Hugo_Symbol~Class+From)

mutRate <- dat_mutRate_tmp


rownames(mutRate) <- mutRate$Hugo_Symbol
col <- c(
  rgb(244,236,224,alpha=255,maxColorValue=255),
  rgb(204,116,92,alpha=255,maxColorValue=255),
  rgb(62,62,93,alpha=255,maxColorValue=255),
  rgb(126,172,149,alpha=255,maxColorValue=255),
  rgb(229,198,143,alpha=255,maxColorValue=255)
)
col_use <- col
names(col_use) <- c("NJMU","OncoSG","TCGA","TMUCIH","Utokyo")
###########################################################################################
subsetmutRate <- function(mutRate=mutRate,lauren=lauren){
  Class <- unique(sapply(strsplit(colnames(mutRate)[-c(1:2,ncol(mutRate))],"_"),"[",2))
  result_use <- data.frame()
  for(g in mutRate$Hugo_Symbol){
    for(c in Class){
      gene <- g
      class <- c
      use_col <- paste0(lauren,"_",class)
      rate <- mutRate[g,use_col]
      df <- data.frame(
        gene <- gene ,
        class <- class , 
        rate <- ifelse(length(rate)>0,rate,NA) 
      )
      result_use <- rbind(result_use,df)
    }
  }
  all_genes <- c("TP53","ARID1A","CDH1","APC","SMAD4","MUC6","PIK3CA",
                 "CTNNB1","RHOA","ERBB2","CFTR","KRAS","MAP2K7","ARID2",
                 "RNF43","TGFBR2","BMP6","FBXW7","CDKN2A","MTRR")
  colnames(result_use) <- c("gene","Class","MutRate")
  result_use <- subset(result_use,Class!="All")
  result_use$gene <- factor(result_use$gene,levels = all_genes)
  result_use <- result_use[order(result_use$gene),]
  return(result_use)
}

###########################################################################################

plotRate <- function( result_use = result_use , col_use = col_use,cluster,scale_params=scale_params ){
  
  result2 <- result_use
  result2$MutRate <- ifelse(is.na(result2$MutRate),0,result2$MutRate)
  result2$value_percent=paste0(round(result2$MutRate * 100),"%",sep="")
  result2$variable <- result2$Class
  result2 <- subset(result2,facety==cluster)
  p <- ggplot(result2,mapping = aes(variable,MutRate,fill=variable))+
    geom_bar(stat = 'identity', position = 'dodge')+
    facet_wrap(vars(gene),ncol=7,drop = FALSE) +
    theme_bw() +
    scale_fill_manual(values=col) +
    theme(strip.text.x = element_text(size = 11)) +
    theme(axis.title =element_text(size = 15),axis.text =element_text(size = 12, color = 'black'))+
    geom_text(aes(label= value_percent , x = variable, y= MutRate ), position=position_dodge(0.9),size = 2, vjust=0 ,color="black", face='bold' , family="Helvetica")+
    xlab("") +
    scale_fill_manual(values=col_use) +
    scale_params+
    theme(
      panel.grid.major = element_blank(),
      panel.grid.minor = element_blank(),
      panel.background = element_blank(),
      axis.text.x = element_blank(),
      axis.title.x = element_blank(),
      axis.ticks.x = element_blank(),
      legend.title = element_blank(),
      legend.text = element_text(size = 12),
      legend.key.width = unit(0.5, "cm"),
      legend.key.height = unit(0.5, "cm"),
      legend.position = "bottom"
    )
  
  return(p)
  
}

###########################################################################################

#IGC,IGC没有Utokyo的，把这个删除
result_use_IGC <- subsetmutRate(mutRate,lauren="IGC")
result_use_IGC <- subset(result_use_IGC,Class!="Utokyo")
print(result_use_IGC)
result_use_IGC$facety <- paste0("Cluster", ceiling(rep(1:20, each = 4) / 7))

scale_params <- scale_y_continuous(
  limits = c(0, 1),
  breaks = seq(0, 1, 0.2),
  labels = as.character(abs(seq(0, 100, 20))))
p1 <- plotRate(result_use=result_use_IGC,col_use=col_use,"Cluster1",scale_params=scale_params)


scale_params <- scale_y_continuous(
  limits = c(0, 0.20),
  breaks = seq(0, 0.2, 0.04),
  labels = as.character(abs(seq(0, 20, 4))))

p2 <- plotRate(result_use=result_use_IGC,col_use=col_use,cluster="Cluster2",scale_params=scale_params)

scale_params <- scale_y_continuous(
  limits = c(0, 0.1),
  breaks = seq(0, 0.1, 0.02),
  labels = as.character(abs(seq(0, 10, 2))))

p3 <- plotRate(result_use=result_use_IGC,col_use=col_use,cluster="Cluster3",scale_params=scale_params)

p <- p1+ p2 +p3+ plot_layout(nrow = 1)

images_name <- paste0(out_path,"/mutRate_byGroup_IGC.pdf")
ggsave(plot=p,filename =images_name,height = 6,width = 20 )



##DGC

result_use_DGC <- subsetmutRate(mutRate,lauren="DGC")
result_use_DGC$facety <- paste0("Cluster", ceiling(rep(1:20, each = 5) / 7))

scale_params <- scale_y_continuous(
  limits = c(0, 0.8),
  breaks = seq(0, 0.8, 0.2),
  labels = as.character(abs(seq(0, 80, 20))))
p1 <- plotRate(result_use=result_use_DGC,col_use=col_use,"Cluster1",scale_params=scale_params)


scale_params <- scale_y_continuous(
  limits = c(0, 0.25),
  breaks = seq(0, 0.2, 0.04),
  labels = as.character(abs(seq(0, 20, 4))))

p2 <- plotRate(result_use=result_use_DGC,col_use=col_use,cluster="Cluster2",scale_params=scale_params)

scale_params <- scale_y_continuous(
  limits = c(0, 0.16),
  breaks = seq(0, 0.16, 0.02),
  labels = as.character(abs(seq(0, 16, 2))))

p3 <- plotRate(result_use=result_use_DGC,col_use=col_use,cluster="Cluster3",scale_params=scale_params)

p <- p1+ p2 +p3+ plot_layout(nrow = 1)

images_name <- paste0(out_path,"/mutRate_byGroup_DGC.pdf")
ggsave(plot=p,filename =images_name,height = 6,width = 20 )


